const logger = require("./logger");
const cfg = require("./cfg");
const batRunner = require("./batRunner");
const dirHelper = require("./dirHelper");

const fs = require("fs");
const path = require("path");
const moment = require("moment");
const schedule = require('node-schedule');

const flagTime = new moment('2017-07-01 00:00:00');
// 十五分钟一个粒度
const granularity = 1000 * 60 * 15;

let log = logger.getLogger('jzt');

/** 
 * 获取合并时间的 checkpoint
 */
let getCheckpoint = function (currentTime) {
    let current = new moment();
    if (currentTime) {
        current = currentTime;
    }
    // 2017-07-01 14:36 => 2017-07-01 14:21
    let checkpoint = Date.parse(current) - granularity;
    // 2017-07-01 14:21 => 2017-07-01 14:15
    checkpoint = flagTime + granularity * Math.floor((checkpoint - flagTime) / granularity);

    log.info("getCheckpoint() =", new moment(checkpoint).format("YYYYMMDDHHmmss"));

    return checkpoint;
}

/**
 * 定义一个比较器，用于文件排序
 */
let compare = function (propertyName) {
    return function (object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if (value2 < value1) {
            return 1;
        }
        else if (value2 > value1) {
            return -1;
        }
        else {
            return 0;
        }
    }
}

/**
 * 将 url 内指定 checpoint 时间范围内的 .ts 文件合并成 .mp4
 */
let concat = function (url) {
    let files = [];
    let endTime = getCheckpoint(new Date());
    // let endTime = getCheckpoint(new moment('2017-06-14 00:16:00'));
    let startTime = endTime - granularity;
    log.info(`开始时间：${(new moment(startTime))}，截至时间：${(new moment(endTime))}`);

    if (fs.existsSync(url)) {
        files = fs.readdirSync(url);
        // 获取需要拼接的视频文件
        let tsFiles = [];
        files.forEach(function (file, index) {
            // let curPath=url + "/" + file;
            let curPath = path.join(url, file);

            if (fs.statSync(curPath).isFile()) {
                // Not Directory
                let stat = fs.statSync(curPath);
                let mtime = Date.parse(stat.mtime);
                if (mtime >= startTime && mtime < endTime && file.endsWith('.ts')) {
                    let tmpPath = path.join(url, file);
                    tmpPath = tmpPath.split('\\').join('/');
                    tsFiles.push({ name: file, path: tmpPath, mtime: mtime });
                    // console.log(`文件"${curPath}"最后修改时间为：${(new moment(mtime))}.`);
                }
            }
        });

        if (tsFiles.length > 0) {
            tsFiles.sort(compare("mtime"));
            tsFiles.forEach((tsFile, index) => {
                log.info(`文件"${tsFile.name}"最后修改时间为：${(new moment(tsFile.mtime))}.`);
            });

            let dirPath = path.join(url, (new moment(startTime)).format('YYYYMM'), '/');
            // 如果文件夹没有需要创建一下
            dirHelper.mkdirsSync(dirPath);
            log.info('Put in the folder: ' + dirPath);

            let concatTexts = tsFiles.map((x) => "file " + x.path);
            log.info('concatTexts: ' + concatTexts);
            // 将 .ts 文件写道 .concat 文件中
            fs.writeFileSync(path.join(dirPath, (new moment(startTime)).format('YYYYMMDDHHmmss') + ".concat"), concatTexts.join('\n'));
            log.info('.concat file has write done: ' + path.join(url, (new moment(startTime)).format('YYYYMMDDHHmmss') + ".concat"));

            // return {concat: 'D:/nginx/html/concat20170701151500.concat', mp4: '20170701151500.mp4'};
            return {
                // concat: 'D:/nginx/html/concat20170701151500.concat'
                concat: path.join(dirPath, (new moment(startTime)).format('YYYYMMDDHHmmss') + ".concat"),
                // mp4: '20170701151500.mp4'
                mp4: path.join(dirPath, (new moment(startTime)).format('YYYYMMDDHHmmss') + ".mp4"),
                bat: path.join(dirPath, (new moment(startTime)).format('YYYYMMDDHHmmss') + ".bat")
            };
        } else {
            log.info('No .ts files match the startTime: ' + (new moment(startTime)).format('YYYYMMDDHHmmss'));
        }
    } else {
        log.error('给定的路径不存在：' + url + '! ')
    }

    return null;
}

/**
 * 执行流程
 */
function repeatTask() {
    // 待拼接视频.ts文件所在文件夹，形如：'D:/Temp/c206'
    let streamFolders = cfg.folders();
    streamFolders.forEach((f, index) => {
        // 拼接符合条件的 .ts 文件，输出 convertInfo: {concat: 'D:/nginx/html/concat20170701151500.concat', mp4: '20170701151500.mp4'}
        let convertInfo = concat(f);
        if (convertInfo) {
            // 得到了 cmd 命令字符串：`${ffmpeg} -f concat -i ${concatFile} -acodec copy -vcodec copy -f mp4 ${outDir}${outFileName}`
            let strCmd = cfg.generateCMD(convertInfo.concat, convertInfo.mp4);
            // 将 cmd 命令写到 20170701151500.bat 文件中
            fs.writeFileSync(convertInfo.bat, strCmd);
            log.info('$BatFile: '+convertInfo.bat+', ConcatFile: '+convertInfo.concat);

            // 执行 .bat 文件
            batRunner.exec(convertInfo.bat);
            // batRunner.exec('D:/Temp/c206/test.bat');
        }
    });
}

// 定时器开动ing。。。
let rule = new schedule.RecurrenceRule();
rule.minute = [3, 18, 33, 48];
let j = schedule.scheduleJob(rule, function () {
    log.info('Running schedule task at: ' + (new moment()).format('YYYYMMDDHHmmss'));
    fs.appendFileSync('schedule.log', (new moment()).format('YYYYMMDDHHmmss') + '\n');

    repeatTask();
});

log.info('Initial done, deal with folders: ' + cfg.folders());
log.info('The program is running...');